<template>
  <div>
    <van-cell @click="onSearch(item)" v-for="item in suggestions" :key="item"  icon="search" >
    <template #title>
      <div v-html="highText(item)"></div>

    </template>
    </van-cell>
  </div>
</template>

<script>
import { getSearchSuggestion } from '@/api/search'
export default {
  name: 'SearchSuggestion',
  props: {
    searchText: {
      type: String,
      required: true
    }
  },
  beforeDestroy () {
    clearInterval(this.setid)
  },
  watch: {
    searchText: {
      immediate: true,
      handler (newVal) {
        if (this.setid) {
          clearInterval(this.setid)
        }
        this.setid = setTimeout(async () => {
          const res = await getSearchSuggestion(newVal)
          this.suggestions = res.options
          console.log(res)
        }, 700)
      }
    }
  },
  data () {
    return {
      suggestions: []
    }
  },

  created () {

  },

  methods: {
    highText (item) {
      const replaceStr = '<span style="color:red">' + this.searchText + '</span>'
      const reg = new RegExp(this.searchText, 'gi')// 动态正则表达式 g 全局 i 不区分大小写
      return item.replace(reg, replaceStr)
    },
    onSearch (item) {
      this.$emit('onSearch', item)
    }
  }
}
</script>

<style scoped lang='less'>

</style>
